# 导入 csv 库
import csv

# 以读方式打开文件
with open("../data/m-a_edges.csv", mode="r", encoding="utf-8-sig") as f:
    
    # 基于打开的文件，创建csv.reader实例
    reader = list(csv.reader(f))
    # print(reader[945])
    # 获取第一行的header
    # header[0] = "source"
    # header[1] = "target"
    header = reader[0][0].split('\t')
    reader.pop(0)
    # 逐行获取数据，并输出
    #row[0] -> mashup; row[1] -> api
    dic = {}
    for rows in reader:
        if len(rows) != 1:
            temp = ''
            for i in rows:
                temp += i
            for i in range(1,len(rows),-1):
                del rows[i]
            rows[0] = temp
        row = rows[0].split('\t')
        # print(row)
        if row[1] in dic:
            dic[row[1]] += 1
        else:
            dic[row[1]] = 1

    header_list = ['Web_API','number']        

# 以写方式打开文件。注意添加 newline=""，否则会在两行数据之间都插入一行空白。
with open("../output/output1/Web_API被使用的次数.csv", mode="w", encoding="utf-8-sig", newline="") as f:                
    # 基于打开的文件，创建 csv.writer 实例
    writer = csv.writer(f)

    # 写入 header。
    # writerow() 一次只能写入一行。
    writer.writerow(header_list)

    for i in dic:
        writer.writerow([i,dic[i]])